package pl.un4giv3n.mightvsmagic.action.clan;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pl.un4giv3n.mightvsmagic.entity.ActivityType;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserActivity;
import pl.un4giv3n.mightvsmagic.utils.ActivityLogUtil;

public class ChangeClanUserPermissionsAction extends ClanAction {

	private static final long serialVersionUID = 1L;
	private Long userId;
	private User selectedUser;
	private boolean moderator;
	private boolean admin;
	private String clanRank;

	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		clan = user.getClan();
		if (clan == null || !isClanAdmin()) {
			entityManager.close();
			addActionError("Wybrany klan nie istnieje lub niewystarczające uprawnienia.");
			return INPUT;
		} else if (userId != null && entityManager.find(User.class, userId) != null) {
			selectedUser = entityManager.find(User.class, userId);
			EntityTransaction transaction = entityManager.getTransaction();
			transaction.begin();
			selectedUser.setClanRank(clanRank);
			selectedUser.setClanAdmin(admin);
			selectedUser.setClanMod(moderator);
			entityManager.merge(selectedUser);
			UserActivity activity = ActivityLogUtil.createActivity(ActivityType.CHANGE_CLAN_PERMISSIONS, user.getId(), "Zmiana uprawnień gracza="+selectedUser);
			entityManager.persist(activity);
			entityManager.flush();
			transaction.commit();
			entityManager.close();
			return SUCCESS;
		} else{
			entityManager.close();
			addActionError("Wybrany użytkownik nie istnieje");
			return INPUT;
		}
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public User getSelectedUser() {
		return selectedUser;
	}

	public void setSelectedUser(User selectedUser) {
		this.selectedUser = selectedUser;
	}

	public boolean isModerator() {
		return moderator;
	}

	public void setModerator(boolean moderator) {
		this.moderator = moderator;
	}

	public boolean isAdmin() {
		return admin;
	}

	public void setAdmin(boolean admin) {
		this.admin = admin;
	}

	public String getClanRank() {
		return clanRank;
	}

	public void setClanRank(String clanRank) {
		this.clanRank = clanRank;
	}

}
